﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YamrSyncDemo.YammerData;

namespace YamrSyncDemo.YammerWrapper
{
    public class YammerWrap
    {
        private YammerConnection connection;

        public YammerWrap(YammerConnection connection)
        {
            this.connection = connection;
        }

        public List<YammerNetwork> GetAccessibleNetworks()
        {
            var response = connection.MakeGetRequest("https://www.yammer.com/api/v1/oauth/tokens.json", connection.AccessToken);
            var networks = JsonConvert.DeserializeObject<List<YammerNetwork>>(response);
            return networks;
        }

        public void PostToApp()
        {
            YammerGraphObject go = new YammerGraphObject();
            go.Activity.Action = "create";
            go.Activity.Actor = new YammerActor("John Doe", "JohnDoe@contoso.com");
            go.Activity.Message = "Hey can we finally get this crazy write stuff working??";

            go.Activity.Users.Add(new YammerActor("Name1", "name1@contoso.com"));
            go.Activity.Users.Add(new YammerActor("Name2", "name2@contoso.com"));

            YammerGraphObjectInstance jo = new YammerGraphObjectInstance();
            jo.Url = "http://www.contoso.com";
            jo.Title = "Demo Link";

            go.Activity.Object = jo;

            string postData = go.ToString();

            #region Working Sample Post Data
            //test3
            //                            postData = @"{
            //    ""activity"": {
            //        ""actor"": {
            //            ""name"": ""Steve Peschka"",
            //            ""email"": ""speschka@contoso.com""
            //        },
            //        ""action"": ""create"",
            //        ""object"": {
            //            ""url"": ""http://localhost:33128/media/detail?id=34"",
            //            ""description"": ""dfdgfdgf"",
            //            ""title"": ""fdgfdgf"",
            //            ""image"": ""https://mug0.assets-yammer.com/mugshot/images/75x75/LBZq1qTjmSd9XkzdkNJnRKCVGQD38MF6""
            //        },
            //        ""private"": ""false"",
            //        ""message"": """",
            //        ""users"": [{""email"":""annew@contoso.com"",""name"":""Anne Wallace""},{""email"":""garthf@contoso.com"",""name"":""Garth Fort""}]
            //    }";
            #endregion

            var response = connection.MakePostRequest(postData, YammerEndpoints.GraphPostUrl, connection.AccessToken, "application/json");
        }

        public void PostMessage()
        {
            #region Post A New Message
            //get info about the current user so you can see the group memberships
            var response = connection.MakeGetRequest(YammerEndpoints.CurrentUserUrl, connection.AccessToken);
            YammerUser yu = YammerUser.GetInstanceFromJson(response);

            //get only the groups out of there
            var groups = from YammerGroupsAndFeeds y in yu.SettingsAndFeedsAndGroups.GroupsAndFeeds
                         where y.Type == "group"
                         select y;

            List<YammerGroupsAndFeeds> myGroups = groups.ToList<YammerGroupsAndFeeds>();

            //enumerate all the groups
            //foreach (YammerGroupsAndFeeds y in myGroups)
            //{
            //    Console.WriteLine(y.GroupID);
            //}

            //just as an example, getting the IT Support group
            var itGroup = from YammerGroupsAndFeeds yg in myGroups
                          where yg.Name == "IT Support"
                          select yg;

            YammerGroupsAndFeeds it = itGroup.First<YammerGroupsAndFeeds>();

            if (it != null)
            {
                //let's post a message now to this group
                bool broadcastToAll = false;

                //form POST - these are the variables:
                //body - The text of the message body.
                //group_id - The ID of the group to which the message should be posted.
                //replied_to_id - The message ID this message is in reply to.
                //direct_to_id - Send a private message directly to the user indicated.
                //broadcast=true - This message should be broadcast to all users. The access token should belong to a verified admin user in paid Yammer networks.
                //topicn - Topics to apply to the message. Can use topic1 through topic20.

                //Console.WriteLine("Type in the message you want posted to the Yammer IT Group then press enter:");
                //string myMessage = Console.ReadLine();

                //string msg = "body=" + myMessage + "&group_id=" +
                //    it.GroupID + "&broadcast=" + broadcastToAll.ToString();

                string msg = "body=Thanks [[user:1504829560]] for your big sale!" + "&group_id=3095986" +
                    "&broadcast=" + broadcastToAll.ToString();

                //try adding the message
                response = connection.MakePostRequest(msg, YammerEndpoints.MessageUrl + ".json", connection.AccessToken);

                if (!string.IsNullOrEmpty(response))
                {
                    YammerMessages newMsg = YammerMessages.GetInstanceFromJson(response);
                    Console.WriteLine("message sent: " + newMsg.Messages[0].MessageContent.PlainText);
                }
            }
            #endregion
        }

        public List<YammerMessage> ReadAllMessages()
        {
            return connection.GetMessagesPaged(YammerEndpoints.MessageUrl + ".json", connection.AccessToken);
        }

        public List<YammerUser> GetAllUsers()
        {
            return connection.GetPagedData<YammerUser>(YammerEndpoints.AllUsersUrl, connection.AccessToken);
        }

        public List<YammerGroup> GetAllGroups()
        {
            return connection.GetPagedData<YammerGroup>(YammerEndpoints.AllGroupsUrl, connection.AccessToken);
        }

        public YammerUser GetOneUser(long userID)
        {
            var response = connection.MakeGetRequest(YammerEndpoints.OneUserUrl.Replace("[:id]", userID.ToString()), connection.AccessToken);
            return YammerUser.GetInstanceFromJson(response);
        }

        public YammerGroupMembers GetGroupMembers(long groupID)
        {
            return connection.GetGroupMembersPaged(groupID, YammerEndpoints.GroupMembersUrl.Replace("[:id]", groupID.ToString()), connection.AccessToken);
        }

        /// <summary>
        /// Get group members if the given group is a public group. If group is no public group the result is still valid but contains no members.
        /// </summary>
        /// <param name="group">Group to retrieve members for</param>
        /// <returns>Group members</returns>
        public YammerGroupMembers GetGroupMembersIfPublic(YammerGroup group)
        {
            YammerGroupMembers members = null;
            if (group.PrivacyLevel.Equals("public", StringComparison.InvariantCultureIgnoreCase))
            {
                members = GetGroupMembers(group.ID);
                Debug.WriteLine("Got public group " + group.Name);
            }
            else
            {
                // create empty group - cannot get members of private gorups
                members = new YammerGroupMembers();
                members.GroupID = group.ID;
                Debug.WriteLine("Skipped private group " + group.Name);
            }

            return members;
        }

        public delegate void AttachmentHandler(YammerFile file, Stream attachmentStream);
        public void GetAttachments(YammerMessage message, AttachmentHandler attachmentHandler)
        {
            if (attachmentHandler == null)
                throw new ArgumentNullException("attachmentHandler");

            foreach (var attachment in message.Attachments)
            {
                if (attachment.Type.Equals("file", StringComparison.InvariantCultureIgnoreCase))
                {
                    // download file info as json
                    var url = attachment.Url + ".json";
                    var response = connection.MakeGetRequest(url, connection.AccessToken);
                    YammerFiles yfs = YammerFiles.GetInstanceFromJson(response);

                    if (yfs.Files.Count > 0)
                    {
                        var file = yfs.Files[0];
                        url = file.DownloadUrl;
                        var resp = connection.MakeGetRequest2(url, connection.AccessToken);
                        var stream = resp.GetResponseStream();
                        attachmentHandler(file, stream);
                        
                        System.Threading.Thread.Sleep(1000);
                    }
                }
            }
        }
    }
}
